<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>余票查询 - 火车票预订系统</title>
    <link rel="stylesheet" href="/home/css/style.css">
    <link rel="stylesheet" href="/home/css/common.css">
    <link rel="stylesheet" href="/home/css/button.css">
    <link rel="stylesheet" type="text/css" href="/home/css/hzw-city-picker.css">
    <script type="text/javascript" src="/home/js/jquery-3.5.1.js"></script>
    <script type="text/javascript" src="/home/js/vue.js"></script>
    <script type="text/javascript" src="/home/js/axios.js"></script>
    <script type="text/javascript" src="/home/js/city-data.js"></script>
    <script type="text/javascript" src="/home/js/hzw-city-picker.min.js"></script>
    <script type="text/javascript" src="/home/js/config.js"></script>
    <style>
        .ticket-query-container {
            min-height: 800px;
            background-color: #f5f5f5;
        }

        .search-section {
            background: white;
            padding: 20px;
            margin: 20px auto;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            max-width: 1200px;
        }

        .search-form {
            display: flex;
            gap: 20px;
            align-items: end;
            flex-wrap: wrap;
        }

        .search-item {
            display: flex;
            flex-direction: column;
            min-width: 150px;
        }

        .search-item label {
            margin-bottom: 5px;
            font-weight: 500;
            color: #333;
        }

        .search-item input, .search-item select {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .search-btn {
            background: #ff8000;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            margin-top: 25px;
        }

        .search-btn:hover {
            background: #e6720c;
        }

        .results-section {
            background: white;
            margin: 20px auto;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            max-width: 1200px;
            overflow: hidden;
        }

        .results-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            font-weight: 500;
        }

        .train-list {
            max-height: 600px;
            overflow-y: auto;
        }

        .train-item {
            display: flex;
            padding: 20px;
            border-bottom: 1px solid #eee;
            align-items: center;
            transition: background-color 0.2s;
        }

        .train-item:hover {
            background-color: #f8f9fa;
        }

        .train-info {
            flex: 2;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .train-number {
            font-size: 18px;
            font-weight: 600;
            color: #0066cc;
            margin-bottom: 5px;
        }

        .train-route {
            font-size: 14px;
            color: #666;
        }

        .time-info {
            text-align: center;
            flex: 1;
        }

        .departure-time {
            font-size: 20px;
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }

        .arrival-time {
            font-size: 16px;
            color: #666;
        }

        .duration {
            font-size: 14px;
            color: #999;
            margin-top: 5px;
        }

        .ticket-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .ticket-type {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .ticket-type:last-child {
            border-bottom: none;
        }

        .ticket-type-name {
            font-size: 14px;
            color: #333;
        }

        .ticket-count {
            font-size: 14px;
            font-weight: 500;
        }

        .available {
            color: #52c41a;
        }

        .limited {
            color: #fa8c16;
        }

        .sold-out {
            color: #ff4d4f;
        }

        .action-btn {
            flex: 0 0 80px;
            text-align: center;
        }

        .book-btn {
            background: #52c41a;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s;
        }

        .book-btn:hover {
            background: #389e0d;
        }

        .book-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .filter-section {
            background: white;
            padding: 15px 20px;
            margin: 20px auto;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            max-width: 1200px;
        }

        .filter-row {
            display: flex;
            gap: 30px;
            align-items: center;
            flex-wrap: wrap;
        }

        .filter-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .filter-item label {
            font-size: 14px;
            color: #666;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin: 20px 0;
            padding: 20px;
        }

        .page-btn {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 4px;
        }

        .page-btn:hover {
            background: #f5f5f5;
        }

        .page-btn.active {
            background: #ff8000;
            color: white;
            border-color: #ff8000;
        }

        .page-btn:disabled {
            background: #f5f5f5;
            color: #ccc;
            cursor: not-allowed;
        }

        .no-results {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .date-picker {
            position: relative;
        }

        .date-display {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            background: white;
            min-width: 150px;
        }

        .city-input {
            position: relative;
            display: inline-block;
            width: 200px;
        }
        
        .city-input input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <!-- 引入顶部文件 -->
    <div id="header"></div>

    <div class="ticket-query-container">
        <!-- 搜索区域 -->
        <div class="search-section">
            <div style="text-align: right; margin-bottom: 15px;">
                <button type="button" class="test-btn" onclick="testBeijingShanghai()" style="margin-right: 10px; background: #52c41a; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer;">测试：京沪高铁</button>
                <button type="button" class="test-btn" onclick="testAllTypes()" style="margin-right: 10px; background: #1890ff; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer;">测试：全类型</button>
                <button type="button" class="test-btn" onclick="testFewTickets()" style="background: #fa8c16; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer;">测试：少量余票</button>
            </div>
            <form id="ticketSearchForm" class="search-form">
                <div class="search-item">
                    <label for="fromCity">出发城市</label>
                    <div class="city-input">
                        <input type="text" id="fromCity" name="fromCity" placeholder="请选择出发城市" readonly autocomplete="off">
                        <!-- 添加隐藏域保存省份和城市代码 -->
                        <input type="hidden" name="fromProvince" id="fromProvince">
                        <input type="hidden" name="fromCityCode" id="fromCityCode">
                    </div>
                </div>
                <div class="search-item">
                    <label for="toCity">到达城市</label>
                    <div class="city-input">
                        <input type="text" id="toCity" name="toCity" placeholder="请选择到达城市" readonly autocomplete="off">
                        <!-- 添加隐藏域保存省份和城市代码 -->
                        <input type="hidden" name="toProvince" id="toProvince">
                        <input type="hidden" name="toCityCode" id="toCityCode">
                    </div>
                </div>

                <div class="search-item">
                    <label for="travelDate">出发日期</label>
                    <div class="date-picker">
                        <input type="date" id="travelDate" name="travelDate">
                    </div>
                </div>

                <div class="search-item">
                    <label for="trainType">车次类型</label>
                    <select id="trainType" name="trainType">
                        <option value="">全部</option>
                        <option value="G">高铁</option>
                        <option value="D">动车</option>
                        <option value="K">快速</option>
                        <option value="T">特快</option>
                        <option value="Z">直达</option>
                    </select>
                </div>

                <button type="submit" class="search-btn">查询余票</button>
            </form>
        </div>

        <!-- 筛选区域 -->
        <div class="filter-section" id="filterSection" style="display: none;">
            <div class="filter-row">
                <div class="filter-item">
                    <label>出发时段:</label>
                    <select id="departureFilter">
                        <option value="">全部</option>
                        <option value="00-06">00:00-06:00</option>
                        <option value="06-12">06:00-12:00</option>
                        <option value="12-18">12:00-18:00</option>
                        <option value="18-24">18:00-24:00</option>
                    </select>
                </div>

                <div class="filter-item">
                    <label>到达时段:</label>
                    <select id="arrivalFilter">
                        <option value="">全部</option>
                        <option value="00-06">00:00-06:00</option>
                        <option value="06-12">06:00-12:00</option>
                        <option value="12-18">12:00-18:00</option>
                        <option value="18-24">18:00-24:00</option>
                    </select>
                </div>

                <div class="filter-item">
                    <label>运行时间:</label>
                    <select id="durationFilter">
                        <option value="">全部</option>
                        <option value="0-2">2小时以内</option>
                        <option value="2-4">2-4小时</option>
                        <option value="4-8">4-8小时</option>
                        <option value="8">8小时以上</option>
                    </select>
                </div>

                <div class="filter-item">
                    <label>仅显示有票:</label>
                    <input type="checkbox" id="onlyWithTickets">
                </div>
            </div>
        </div>

        <!-- 结果区域 -->
        <div class="results-section" id="resultsSection" style="display: none;">
            <div class="results-header" id="resultsHeader">
                查询结果
            </div>

            <div class="train-list" id="trainList">
                <!-- 车次列表将在这里动态生成 -->
            </div>

            <!-- 分页 -->
            <div class="pagination" id="pagination" style="display: none;">
                <button class="page-btn" id="prevPage">上一页</button>
                <span id="pageInfo">第 1 页，共 1 页</span>
                <button class="page-btn" id="nextPage">下一页</button>
            </div>
        </div>
    </div>

    <!-- 引入底部文件 -->
    <div id="footer"></div>

    <script src="/home/js/jquery.min.js"></script>
    <script src="/home/js/vue.js"></script>
    <script src="/home/js/city-data.js"></script>
    <script src="/home/js/hzw-city-picker.min.js"></script>
    <script>
        $(document).ready(function() {
            // 页面初始化
            initPage();

            // 绑定事件
            bindEvents();
        });

        function initPage() {
            // 设置默认日期为今天
            const today = new Date().toISOString().split('T')[0];
            $('#travelDate').val(today);

            // 加载公共头部和底部
            loadHeaderFooter();
        }

        function loadHeaderFooter() {
            // 加载头部
            $.get('/home/header.html', function(data) {
                $('#header').html(data);
            });

            // 加载底部
            $.get('/home/footer.html', function(data) {
                $('#footer').html(data);
            });
        }

        function bindEvents() {
            // 搜索表单提交
            $('#ticketSearchForm').on('submit', function(e) {
                e.preventDefault();
                searchTickets();
            });

            // 初始化城市选择器
            initCityPickers();

            // 筛选条件变化
            $('#departureFilter, #arrivalFilter, #durationFilter, #onlyWithTickets').on('change', function() {
                filterAndSortResults();
            });

            // 分页
            $('#prevPage').on('click', function() {
                if (currentPage > 1) {
                    currentPage--;
                    displayCurrentPage();
                }
            });

            $('#nextPage').on('click', function() {
                if (currentPage < totalPages) {
                    currentPage++;
                    displayCurrentPage();
                }
            });
        }

        // 全局变量
        let allResults = [];
        let filteredResults = [];
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 1;

        function searchTickets() {
            const searchParams = {
                fromCity: $('#fromCity').val().trim(),
                toCity: $('#toCity').val().trim(),
                travelDate: $('#travelDate').val(),
                trainType: $('#trainType').val()
            };

            // 验证必填字段
            if (!searchParams.fromCity || !searchParams.toCity || !searchParams.travelDate) {
                alert('请填写完整的查询信息');
                return;
            }

            // 显示加载状态
            showLoading();

            // 发送请求
            axios.post('/api/train/ticket-query', searchParams)
                .then(function(response) {
                    hideLoading();
                    
                    if (response.data.code === 200) {
                        allResults = response.data.data || [];
                        currentPage = 1;
                        filterAndSortResults();
                    } else {
                        // 使用模拟数据作为演示
                        console.log('API响应错误，使用模拟数据演示');
                        allResults = getMockData(searchParams);
                        currentPage = 1;
                        filterAndSortResults();
                    }
                })
                .catch(function(error) {
                    hideLoading();
                    console.error('查询请求失败，使用模拟数据演示:', error);
                    // 使用模拟数据作为演示
                    allResults = getMockData(searchParams);
                    currentPage = 1;
                    filterAndSortResults();
                });
        }

        function filterAndSortResults() {
            // 应用筛选条件
            filteredResults = [...allResults];

            // 车次类型筛选
            const trainType = $('#trainType').val();
            if (trainType) {
                filteredResults = filteredResults.filter(train => train.trainNumber.startsWith(trainType));
            }

            // 出发时段筛选
            const departureFilter = $('#departureFilter').val();
            if (departureFilter) {
                const [start, end] = departureFilter.split('-');
                filteredResults = filteredResults.filter(train => {
                    const hour = parseInt(train.departureTime.split(':')[0]);
                    return hour >= parseInt(start) && hour < parseInt(end);
                });
            }

            // 到达时段筛选
            const arrivalFilter = $('#arrivalFilter').val();
            if (arrivalFilter) {
                const [start, end] = arrivalFilter.split('-');
                filteredResults = filteredResults.filter(train => {
                    const hour = parseInt(train.arrivalTime.split(':')[0]);
                    return hour >= parseInt(start) && hour < parseInt(end);
                });
            }

            // 运行时间筛选
            const durationFilter = $('#durationFilter').val();
            if (durationFilter) {
                if (durationFilter === '8') {
                    filteredResults = filteredResults.filter(train => {
                        const duration = parseFloat(train.duration.replace('小时', ''));
                        return duration >= 8;
                    });
                } else {
                    const [min, max] = durationFilter.split('-');
                    filteredResults = filteredResults.filter(train => {
                        const duration = parseFloat(train.duration.replace('小时', ''));
                        return duration >= parseFloat(min) && duration < parseFloat(max);
                    });
                }
            }

            // 仅显示有票
            if ($('#onlyWithTickets').is(':checked')) {
                filteredResults = filteredResults.filter(train => {
                    return train.tickets.some(ticket => ticket.count > 0);
                });
            }

            // 按出发时间排序
            filteredResults.sort((a, b) => {
                return a.departureTime.localeCompare(b.departureTime);
            });

            // 显示结果
            displayResults();
        }

        function displayResults() {
            if (filteredResults.length === 0) {
                showNoResults();
                return;
            }

            // 计算分页
            totalPages = Math.ceil(filteredResults.length / pageSize);

            // 显示筛选和分页控件
            $('#filterSection').show();
            $('#resultsSection').show();
            $('#pagination').show();

            // 更新结果标题
            const searchParams = {
                fromCity: $('#fromCity').val(),
                toCity: $('#toCity').val(),
                travelDate: $('#travelDate').val()
            };
            $('#resultsHeader').text(
                `${searchParams.fromCity} → ${searchParams.toCity} (${searchParams.travelDate}) - 找到 ${filteredResults.length} 个车次`
            );

            // 显示当前页
            displayCurrentPage();
        }

        function displayCurrentPage() {
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = Math.min(startIndex + pageSize, filteredResults.length);
            const currentPageResults = filteredResults.slice(startIndex, endIndex);

            // 生成车次列表HTML
            const trainListHtml = currentPageResults.map(train => generateTrainItemHtml(train)).join('');
            $('#trainList').html(trainListHtml);

            // 更新分页信息
            $('#pageInfo').text(`第 ${currentPage} 页，共 ${totalPages} 页`);

            // 更新分页按钮状态
            $('#prevPage').prop('disabled', currentPage === 1);
            $('#nextPage').prop('disabled', currentPage === totalPages);
        }

        function generateTrainItemHtml(train) {
            const ticketsHtml = train.tickets.map(ticket => {
                const countClass = ticket.count === 0 ? 'sold-out' :
                                 ticket.count <= 10 ? 'limited' : 'available';
                const countText = ticket.count === 0 ? '无票' :
                                ticket.count <= 10 ? `剩${ticket.count}张` : '有票';

                return `
                    <div class="ticket-type">
                        <span class="ticket-type-name">${ticket.typeName}</span>
                        <span class="ticket-count ${countClass}">${countText}</span>
                    </div>
                `;
            }).join('');

            const bookBtnDisabled = train.tickets.every(ticket => ticket.count === 0) ? 'disabled' : '';

            return `
                <div class="train-item">
                    <div class="train-info">
                        <div>
                            <div class="train-number">${train.trainNumber}</div>
                            <div class="train-route">${train.fromStation} → ${train.toStation}</div>
                        </div>
                    </div>

                    <div class="time-info">
                        <div class="departure-time">${train.departureTime}</div>
                        <div class="arrival-time">${train.arrivalTime}</div>
                        <div class="duration">${train.duration}</div>
                    </div>

                    <div class="ticket-info">
                        ${ticketsHtml}
                    </div>

                    <div class="action-btn">
                        <button class="book-btn" ${bookBtnDisabled} onclick="bookTicket('${train.trainNumber}')">
                            预订
                        </button>
                    </div>
                </div>
            `;
        }

        function showLoading() {
            $('#resultsSection').hide();
            $('#filterSection').hide();
            $('#trainList').html('<div class="loading">正在查询中...</div>');
            $('#resultsSection').show();
        }

        function hideLoading() {
            $('#resultsSection').show();
        }

        function showNoResults() {
            $('#filterSection').show();
            $('#resultsSection').show();
            $('#trainList').html(`
                <div class="no-results">
                    <h3>未找到符合条件的车次</h3>
                    <p>请尝试调整搜索条件或日期</p>
                </div>
            `);
            $('#pagination').hide();
        }

        function showError(message) {
            $('#filterSection').hide();
            $('#resultsSection').show();
            $('#trainList').html(`
                <div class="no-results">
                    <h3>查询失败</h3>
                    <p>${message}</p>
                </div>
            `);
            $('#pagination').hide();
        }

        function initCityPickers() {
             // 初始化省份-城市选择器
             var fromCityPicker = new HzwCityPicker({
                 data: data,
                 target: 'fromCity',
                 valType: 'k-v',
                 hideCityInput: {
                     name: 'fromCityCode',
                     id: 'fromCityCode'
                 },
                 hideProvinceInput: {
                     name: 'fromProvince',
                     id: 'fromProvince'
                 },
                 callback: function() {
                     // 当选择城市后，手动触发change事件
                     $('#fromCity').trigger('change');
                 }
             });
             fromCityPicker.init();
             
             var toCityPicker = new HzwCityPicker({
                 data: data,
                 target: 'toCity',
                 valType: 'k-v',
                 hideCityInput: {
                     name: 'toCityCode',
                     id: 'toCityCode'
                 },
                 hideProvinceInput: {
                     name: 'toProvince',
                     id: 'toProvince'
                 },
                 callback: function() {
                     // 当选择城市后，手动触发change事件
                     $('#toCity').trigger('change');
                 }
             });
             toCityPicker.init();
         }



        function bookTicket(trainNumber) {
            alert(`预订车次: ${trainNumber}\n功能开发中...`);
        }
        
        // 模拟数据生成函数
        function getMockData(searchParams) {
            const { fromCity, toCity, travelDate, trainType } = searchParams;
            
            // 基础车次模板
            const trainTemplates = [
                {
                    trainNumber: 'G1',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '08:00',
                    arrivalTime: '11:30',
                    duration: '3.5小时',
                    tickets: [
                        { typeName: '二等座', count: 25 },
                        { typeName: '一等座', count: 8 },
                        { typeName: '商务座', count: 3 }
                    ]
                },
                {
                    trainNumber: 'G2',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '10:30',
                    arrivalTime: '14:15',
                    duration: '3.75小时',
                    tickets: [
                        { typeName: '二等座', count: 0 },
                        { typeName: '一等座', count: 2 },
                        { typeName: '商务座', count: 0 }
                    ]
                },
                {
                    trainNumber: 'G3',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '14:20',
                    arrivalTime: '18:05',
                    duration: '3.75小时',
                    tickets: [
                        { typeName: '二等座', count: 15 },
                        { typeName: '一等座', count: 0 },
                        { typeName: '商务座', count: 1 }
                    ]
                },
                {
                    trainNumber: 'G4',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '16:45',
                    arrivalTime: '20:30',
                    duration: '3.75小时',
                    tickets: [
                        { typeName: '二等座', count: 30 },
                        { typeName: '一等座', count: 12 },
                        { typeName: '商务座', count: 5 }
                    ]
                },
                {
                    trainNumber: 'D1',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '07:15',
                    arrivalTime: '12:45',
                    duration: '5.5小时',
                    tickets: [
                        { typeName: '二等座', count: 8 },
                        { typeName: '一等座', count: 3 },
                        { typeName: '卧铺', count: 0 }
                    ]
                },
                {
                    trainNumber: 'D2',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '13:20',
                    arrivalTime: '18:50',
                    duration: '5.5小时',
                    tickets: [
                        { typeName: '二等座', count: 0 },
                        { typeName: '一等座', count: 0 },
                        { typeName: '卧铺', count: 2 }
                    ]
                },
                {
                    trainNumber: 'K1',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '06:30',
                    arrivalTime: '18:25',
                    duration: '11.92小时',
                    tickets: [
                        { typeName: '硬座', count: 45 },
                        { typeName: '硬卧', count: 12 },
                        { typeName: '软卧', count: 6 }
                    ]
                },
                {
                    trainNumber: 'K2',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '19:45',
                    arrivalTime: '07:20+1',
                    duration: '11.58小时',
                    tickets: [
                        { typeName: '硬座', count: 0 },
                        { typeName: '硬卧', count: 3 },
                        { typeName: '软卧', count: 1 }
                    ]
                },
                {
                    trainNumber: 'T1',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '09:10',
                    arrivalTime: '15:30',
                    duration: '6.33小时',
                    tickets: [
                        { typeName: '硬座', count: 20 },
                        { typeName: '硬卧', count: 8 },
                        { typeName: '软卧', count: 4 }
                    ]
                },
                {
                    trainNumber: 'Z1',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '22:20',
                    arrivalTime: '05:45+1',
                    duration: '7.42小时',
                    tickets: [
                        { typeName: '硬座', count: 35 },
                        { typeName: '硬卧', count: 15 },
                        { typeName: '软卧', count: 7 }
                    ]
                },
                {
                    trainNumber: 'G5',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '18:30',
                    arrivalTime: '22:10',
                    duration: '3.67小时',
                    tickets: [
                        { typeName: '二等座', count: 5 },
                        { typeName: '一等座', count: 1 },
                        { typeName: '商务座', count: 0 }
                    ]
                },
                {
                    trainNumber: 'G6',
                    fromStation: fromCity,
                    toStation: toCity,
                    departureTime: '20:15',
                    arrivalTime: '23:55',
                    duration: '3.67小时',
                    tickets: [
                        { typeName: '二等座', count: 18 },
                        { typeName: '一等座', count: 7 },
                        { typeName: '商务座', count: 2 }
                    ]
                }
            ];
            
            // 根据车次类型筛选模板
            let filteredTemplates = trainTemplates;
            if (trainType) {
                filteredTemplates = trainTemplates.filter(train => train.trainNumber.startsWith(trainType));
                // 如果筛选后为空，返回所有模板
                if (filteredTemplates.length === 0) {
                    filteredTemplates = trainTemplates;
                }
            }
            
            // 创建随机数量的车次（8-15个）
            const numTrains = Math.floor(Math.random() * 8) + 8;
            const selectedTrains = [];
            
            for (let i = 0; i < numTrains && i < filteredTemplates.length; i++) {
                const template = filteredTemplates[i];
                
                // 随机调整票数（让数据更真实）
                const tickets = template.tickets.map(ticket => ({
                    ...ticket,
                    count: Math.max(0, Math.floor(Math.random() * 50))
                }));
                
                // 随机选择一些车次作为售罄（20%概率）
                const isSoldOut = Math.random() < 0.2;
                if (isSoldOut) {
                    tickets.forEach(ticket => ticket.count = 0);
                }
                
                selectedTrains.push({
                    trainNumber: template.trainNumber,
                    fromStation: template.fromStation,
                    toStation: template.toStation,
                    departureTime: template.departureTime,
                    arrivalTime: template.arrivalTime,
                    duration: template.duration,
                    tickets: tickets
                });
            }
            
            // 根据搜索的日期和时间调整一些逻辑
            const today = new Date().toISOString().split('T')[0];
            if (travelDate === today) {
                // 如果是今天，添加一些当前时间之后的车次
                const currentHour = new Date().getHours();
                selectedTrains.forEach(train => {
                    const trainHour = parseInt(train.departureTime.split(':')[0]);
                    if (trainHour < currentHour) {
                        // 已经出发的车次，标记为无票
                        train.tickets.forEach(ticket => ticket.count = 0);
                    }
                });
            }
            
            return selectedTrains;
        }
        
        // 测试函数
        function testBeijingShanghai() {
            $('#fromCity').val('北京');
            $('#toCity').val('上海');
            $('#travelDate').val(new Date().toISOString().split('T')[0]);
            $('#trainType').val('G');
            searchTickets();
        }
        
        function testAllTypes() {
            $('#fromCity').val('北京');
            $('#toCity').val('广州');
            $('#travelDate').val(new Date().toISOString().split('T')[0]);
            $('#trainType').val('');
            searchTickets();
        }
        
        function testFewTickets() {
            $('#fromCity').val('深圳');
            $('#toCity').val('杭州');
            $('#travelDate').val(new Date().toISOString().split('T')[0]);
            $('#trainType').val('D');
            searchTickets();
        }
    </script>
</body>
</html>
